package com.farsunset.cim.nio.filter;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.mutual.SentBody;
import com.kuaigou.cim.util.JSONHelper;
/**
 *  服务端接收消息解码，可在此解密消息
 *  @author 3979434@qq.com
 *
 */
public class ServerMessageDecoder extends FrameDecoder  {
	
	protected final Logger logger = Logger.getLogger(ServerMessageDecoder.class);

	@Override
	protected Object decode(ChannelHandlerContext arg0, Channel channel,ChannelBuffer  buffer) throws Exception {
		
		 
		int length = buffer.readableBytes();
		
		/**
		 * CIMConstant.MESSAGE_SEPARATE 为消息界限
		 * 当一次收到多个消息时，以此分隔解析多个消息
		 */
		if (buffer.readable()&&length > 0) {			
			byte[] data = new byte[length];
			buffer.readBytes(data);
			String message = new String(new String(data,CIMConstant.ENCODE_UTF8)); 
			logger.debug("[ServerMessageDecoder]:"+message);			
			SentBody body = new SentBody();			
			body = JSONHelper.jsonToEntity(message, SentBody.class);			
	        data = null;
	        message = null;
	        return body;
		}	
		
		/**
		 * CIMConstant.FLEX_DATA_SEPARATE 为FLEX客户端socket验证消息界限
		 * 
		 */
		if (buffer.readable()&& length > 0 &&  CIMConstant.FLEX_DATA_SEPARATE == buffer.getByte(length-1)) {
			
			byte[] data = new byte[length-1];
			buffer.readBytes(data);
			String message = new String(new String(data,CIMConstant.ENCODE_UTF8));
			
			logger.debug("[ServerMessageDecoder]:"+message);
			
			//将末尾的消息分隔符读取掉
			buffer.readByte();
			data = null;
			
			return message;
		}
        
		return null;
	}

}
